const {MoveNewRoom} = require("./Param");
const {
    findFlagList,
    findRoleCreepsByAll,
    findStore,
    findBuilding,
    findRepair,
    bestFindClose,
    findRoleCreepsByRoom
} = require("./Find");
const {create} = require("./Create");
//外矿收集兵运行逻辑
module.exports.outHarvest = function (creep) {
    //迁徙逻辑
    let mustMove = false;
    for (let room of MoveNewRoom) {
        if (creep.memory.harvestRoom === room) {
            mustMove = true;
            break;
        }
    }
    if (mustMove) {
        let flag = findFlagList("resource_move", 1);
        if (flag) {
            creep.say("🚙")
            creep.bestMove(flag)
        }
        return;
    }
    //无需迁徙
    creep.initFull();
    let source = Game.getObjectById(creep.memory.source);
    let outRepairList = findRoleCreepsByAll("外部维修兵").filter(outRepair => outRepair.memory.source === creep.memory.harvestRoom);
    let spawn = Game.spawns[creep.memory.createSpawn];
    if (creep.room.name === creep.memory.harvestRoom && !spawn.spawning && !creep.room.controller.my && outRepairList.length === 0) {
        let available = spawn.room.energyCapacityAvailable;
        if (outRepairList.length === 0 && Game.rooms[creep.memory.harvestRoom] && !spawn.room.mustSpawning && Game.time % 5 === 0) {
            if (available > 850) {
                create(null, "外部维修兵", 2, spawn, creep.room.name);
            } else {
                create(null, "外部维修兵", 1, spawn, creep.room.name);
            }
        }
    }
    if (!creep.memory.isFull) {//如果未满
        creep.memory.backHome = false;
        if (creep.room.name === creep.memory.harvestRoom) {
            creep.say("🪓");
            creep.bestHarvest(source);
            return;
        }
        if (source !== null) {
            creep.say("🚙")
            creep.bestMove(source);
            return;
        }
        creep.bestMove(new RoomPosition(25, 25, creep.memory.harvestRoom))
        return;
    }
    //如果已满
    //如果存在能量和容器,先放着
    let containList = creep.pos.findInRange(findStore(Game.rooms[creep.memory.harvestRoom], -1), 3);
    if (source.energy > 0 && containList.length > 0) {
        creep.say("🥫")
        let transStore = creep.findBindClose(containList);
        creep.bestTrans(transStore);
        return;
    }
    creep.say("🚮")
    creep.drop(RESOURCE_ENERGY);
}
//外部搬运兵逻辑
module.exports.outTrans = function (creep) {
    creep.initFull()
    //已满
    if (creep.memory.isFull) {
        //回城
        backHome(creep);
        return;
    }
    //背包未满
    if (creep.room.name !== creep.memory.source) {
        creep.say("🚙")
        if (creep.memory.source !== null) {
            let stopList = findFlagList("stop").filter(flag => flag.room && flag.room.name === creep.memory.source)
            if (stopList.length > 0) {
                creep.bestMove(stopList[0]);
            }
        }
        return;
    }
    //到达该房间
    //存在绑定
    if (creep.memory.bindId) {
        let bindSource = Game.getObjectById(creep.memory.bindId);
        if (bindSource === null) {
            creep.memory.bindId = undefined;
            return;
        }
        if (bindSource.resourceType) {//是否为地上资源
            creep.say("📦")
            creep.bestPickup(bindSource);
            return;
        }
        //是否为过期creep
        creep.say("⚰")
        let haveOther;
        for (let storeKey in creep.store) {
            haveOther = storeKey;
            break;
        }
        creep.bestWithdraw(bindSource, haveOther)
        return;
    }
    let outTransList = findRoleCreepsByRoom(creep.room, "外部搬运兵");
    let droppedResource = bestFindClose(creep, creep.room.find(FIND_DROPPED_RESOURCES, {
        filter: (source) => {
            for (let outTrans of outTransList) {
                if (outTrans.memory.bindId === source.id) {
                    return false;
                }
            }
            return source.amount > 100
        }
    }));
    if (droppedResource) {
        creep.memory.bindId = droppedResource.id;
        return;
    }
    //如果地上有过期creep
    let deadCreep = bestFindClose(creep, creep.room.find(FIND_TOMBSTONES, {
        filter: (tombstone) => {
            for (let outTrans of outTransList) {
                if (outTrans.memory.bindId === tombstone.id) {
                    return false;
                }
            }
            let haveOther = false;
            for (let storeKey in tombstone.store) {
                if (tombstone.store.getUsedCapacity(storeKey) > 0) {
                    haveOther = true;
                    break;
                }
            }
            return haveOther
        }
    }))
    if (deadCreep) {
        creep.memory.bindId = deadCreep.id;
        return;
    }
    let containerList = creep.room.find(FIND_STRUCTURES, {filter: structure => structure.structureType === STRUCTURE_CONTAINER && structure.usedStore() > 200});
    containerList.sort((a, b) => a.freeStore() - b.freeStore())
    let store = containerList[0];
    if (store) {
        creep.say("🔋")
        creep.bestWithdraw(store)
        return;
    }
    let outHarvestList = findRoleCreepsByRoom(creep.room, "外矿收集兵");
    if (outHarvestList.length > 0) {
        creep.say("🚙")
        creep.bestMove(outHarvestList[0]);
    }
}
//外部维修兵运行逻辑
module.exports.outRepair = function (creep) {
    //迁徙逻辑
    let mustMove = false;
    for (let room of MoveNewRoom) {
        if (creep.memory.source === room) {
            mustMove = true;
            break;
        }
    }
    if (mustMove) {
        let flag = findFlagList("resource_move", 1);
        if (flag) {
            creep.say("🚙")
            creep.bestMove(flag)
        }
        return;
    }
    if(creep.room.name === creep.memory.source){
        if (creep.getActiveBodyparts(ATTACK) > 0) {
            let hostileList = creep.room.find(FIND_HOSTILE_CREEPS);
            if (hostileList.length > 0) {
                creep.say("💢");
                creep.bestAttack(bestFindClose(creep, hostileList))
                return;
            }
        }
        let towerList = creep.room.find(FIND_HOSTILE_STRUCTURES, {filter: site => site.structureType === STRUCTURE_TOWER || site.structureType ===STRUCTURE_INVADER_CORE});
        if (towerList.length > 0) {
            creep.say("💢");
            creep.bestAttack(bestFindClose(creep, towerList));
            return;
        }
        if (creep.getActiveBodyparts(CARRY) <= 0) {
            creep.suicide();
        }
        let droppedList = creep.room.find(FIND_DROPPED_RESOURCES);
        let allDropped = 0;
        for (let source of droppedList) {
            allDropped += source.amount;
        }
    }
    let spawn = Game.spawns[creep.memory.createSpawn];
    let available = spawn.room.energyCapacityAvailable;
    if (creep.room.name === creep.memory.source && !spawn.spawning && Game.time % 5 === 0 && !creep.room.controller.my) {
        let outRepairList = findRoleCreepsByAll("外部维修兵").filter(outRepair => outRepair.memory.source === creep.room.name && outRepair.ticksToLive > 60);
        if (outRepairList.length < 1) {
            if (available > 850) {
                create(null, "外部维修兵", 2, spawn, creep.room.name);
            } else {
                create(null, "外部维修兵", 1, spawn, creep.room.name);
            }
        }
        let outTransList = findRoleCreepsByAll("外部搬运兵").filter(outTrans => outTrans.memory.source === creep.room.name && outTrans.ticksToLive > 60);
        if (creep.room.controller.my) {
        } else if (outTransList.length < 2 && allDropped > 1000) {
            if (allDropped <= 1500) {
                if (available >= 1000) {
                    create(null, "外部搬运兵", 2, spawn, creep.room.name);
                } else {
                    create(null, "外部搬运兵", 1, spawn, creep.room.name);
                }
                return;
            }
            if (allDropped <= 2500) {
                if (available >= 2000) {
                    create(null, "外部搬运兵", 3, spawn, creep.room.name);
                } else if (available >= 1000) {
                    create(null, "外部搬运兵", 2, spawn, creep.room.name);
                } else {
                    create(null, "外部搬运兵", 1, spawn, creep.room.name);
                }
                return;
            }
            if (available > 2500) {
                create(null, "外部搬运兵", 4, spawn, creep.room.name);
            } else if (available >= 2000) {
                create(null, "外部搬运兵", 3, spawn, creep.room.name);
            } else if (available >= 1000) {
                create(null, "外部搬运兵", 2, spawn, creep.room.name);
            } else {
                create(null, "外部搬运兵", 1, spawn, creep.room.name);
            }
        }
    }
    creep.initFull()
//已满
    if (creep.memory.isFull) {
        //存在维修先维修
        let repairList = findRepair(Game.rooms[creep.memory.source]).filter(site => site.hits / site.hitsMax < 0.5 && site.structureType === STRUCTURE_ROAD);
        if (repairList.length > 0) {
            creep.say("👨‍🔧");
            let closeRepair = creep.findBindClose(repairList);
            creep.bestRepair(closeRepair);
            return;
        }
        //存在建造就建造
        let buildingList = findBuilding(Game.rooms[creep.memory.source]);
        if (buildingList.length > 0) {//如果需要建筑优先建筑
            creep.say("🚧");
            creep.building();
            return;
        }
        if (creep.room.controller.my) {
            creep.say("✨");
            creep.bestUpController(creep.room.controller);
        }
        creep.moveToStop();
        return;
    }
//背包未满
    if (creep.room.name !== creep.memory.source) {
        creep.say("🚙")
        creep.bestMove(new RoomPosition(25, 25, creep.memory.source));
        return;
    }
    if (Game.getObjectById(creep.memory.bindId) === null || Game.getObjectById(creep.memory.bindId) === undefined) {
        creep.memory.bindId = undefined;
    }
    let droppedResourceList = creep.room.find(FIND_DROPPED_RESOURCES).filter(source => source.amount > 100);
    if (droppedResourceList.length > 0) {
        creep.say("📦")
        creep.bestPickup(creep.findBindClose(droppedResourceList));
        return;
    }
    let deadCreepList = creep.room.find(FIND_TOMBSTONES);
    if (deadCreepList.length > 0) {
        creep.say("⚰")
        let haveOther;
        for (let storeKey in creep.store) {
            haveOther = storeKey;
            break;
        }
        creep.bestWithdraw(creep.findBindClose(deadCreepList), haveOther)
        return;
    }
    creep.bestGetSource();
}
//预订兵运行逻辑
module.exports.reserve = function (creep) {
    if (creep.room.name !== creep.memory.reserveRoom) {
        creep.say("🚙")
        creep.bestOutMove(new RoomPosition(25, 25, creep.memory.reserveRoom));
        return
    }
    //在指定房间
    if (!creep.room.controller.sign || creep.room.controller.sign.username !== "BLACKJUNWIN") {
        creep.signController(creep.room.controller, "");
        if (creep.signController(creep.room.controller, "Peaceful development✨!") === ERR_NOT_IN_RANGE) {
            creep.bestMove(creep.room.controller);
        }
    }
    creep.say("🏴‍☠️");
    let reserveFlag = findFlagList("reserve").filter(flag => flag.pos.roomName === creep.memory.reserveRoom)[0]
    if (creep.pos.inRangeTo(reserveFlag, 3)) {
        creep.bestReserveController(creep.room.controller);
    } else {
        creep.bestMove(reserveFlag);
    }
}
//占领兵运行逻辑
module.exports.occupy = function (creep) {
    let hostileController = creep.room.controller;
    let claimPos = findFlagList("occupy", 1);
    //如果房间内存在可占领控制器,且存在旗帜
    if (claimPos && hostileController && claimPos.pos.roomName === creep.room.name) {
        if (!creep.room.controller.sign || creep.room.controller.sign.username !== "BLACKJUNWIN") {
            creep.signController(creep.room.controller, "");
            if (creep.signController(creep.room.controller, "Peaceful development✨!") === ERR_NOT_IN_RANGE) {
                creep.bestMove(creep.room.controller);
            }
        }
        creep.say("🏴‍☠️");
        creep.bestClaimController(hostileController);
        return;
    }
    creep.say("🚙")
    if (claimPos) {
        if (!creep.pos.inRangeTo(claimPos, 3)) {
            creep.bestMove(claimPos)
        }
    }
}
//守护兵运行逻辑
module.exports.guard = guard = (creep) => {
    if (!creep.memory.bindId) {//绑定了伙伴后再前往守护
        let guardList = findRoleCreepsByRoom(creep.room, "守护兵").filter(guardCreep => guardCreep.id !== creep.id);
        if (guardList.length > 0) {
            creep.memory.bindId = guardList[0].id;
            guardList[0].memory.bindId = creep.id;
        }
        return;
    }
    //默认治疗最近血量最少的creep
    let nearbyCreeps = creep.room.find(FIND_MY_CREEPS, {filter: nearbyCreep => nearbyCreep.hits < nearbyCreep.hitsMax})
    let nearbyHit = creep.pos.findInRange(nearbyCreeps, 2)
    if (nearbyHit.length > 0) {
        creep.say("🥤");
        nearbyHit.sort((a, b) => a.hits - b.hits)
        creep.bestHeal(nearbyHit[0]);
    } else {
        creep.heal(creep);
    }
    let guardRoomName = creep.memory.guardRoom
    if (creep.room.name !== guardRoomName) {//不在该房间先去该房间
        creep.say("🚙")
        creep.bestMove(new RoomPosition(25, 25, guardRoomName))
        return;
    }
    //如果已经在房间内
    //3格范围内存在敌兵,直接先攻击
    let npcCreep = creep.pos.findInRange(creep.room.find(FIND_HOSTILE_CREEPS), 3)[0];
    if (npcCreep) {
        creep.say("💢");
        if (creep.bestAttack(npcCreep) === ERR_INVALID_TARGET) {
            creep.memory.closeId = undefined;
        }
        return;
    }
    //存在绑定,直接前往绑定对象
    if (creep.memory.closeId) {
        creep.say("🚙干架");
        if (Game.getObjectById(creep.memory.closeId) === null) {
            creep.memory.closeId = undefined;
            return;
        }
        let status = creep.moveByPath(creep.room.findPath(creep.pos, Game.getObjectById(creep.memory.closeId).pos, {swampCost: 5}));
        if (status === -7) {
            creep.memory.closeId = undefined;
        }
        return;
    }
    //如果存在敌兵,先去击杀敌兵
    let allGuardList = findRoleCreepsByRoom(creep.room, "守护兵");
    let hostileList = creep.room.find(FIND_HOSTILE_CREEPS).filter(item => {
        let noBind = true;
        for (let guardItem of allGuardList) {
            if (guardItem.memory.closeId === item.id) {
                noBind = false;
                break;
            }
        }
        return noBind;
    });
    if (hostileList.length > 0) {
        creep.findBindClose(hostileList);
        return;
    }
    //去最近的npc生成母巢
    let keeperLairList = creep.room.find(FIND_HOSTILE_STRUCTURES, {filter: site => site.structureType === STRUCTURE_KEEPER_LAIR}).filter(site => {
        let noBind = true;
        for (let guardItem of allGuardList) {
            if (guardItem.memory.closeId === site.id) {
                noBind = false;
                break;
            }
        }
        return noBind;
    })
    keeperLairList.sort((a, b) => a.ticksToSpawn - b.ticksToSpawn)
    creep.memory.closeId = keeperLairList[0];
}
/**
 * 通过搬运回城逻辑
 */
module.exports.backHome = backHome = (creep) => {
    let spawn = Game.spawns[creep.memory.createSpawn];
    if (spawn.room.name !== creep.room.name) {
        creep.say("🔙")
        creep.bestOutMove(spawn)
        return
    }
    //如果已经到达房间
    let containerList = creep.room.find(FIND_STRUCTURES, {
        filter: (structure) => {
            return (structure.structureType === STRUCTURE_CONTAINER || structure.structureType === STRUCTURE_STORAGE || structure.structureType === STRUCTURE_LINK) && structure.freeStore() > 0;
        },
    });
    let transStore = creep.findBindClose(containerList);
    if (transStore) {
        creep.say("🥫")
        creep.bestTrans(transStore);
    }
}